var express = require("express");
var OpenAI = require("openai");
var router = express.Router();

const openai = new OpenAI({
  baseURL: "https://api.deepseek.com",
  apiKey: "sk-c84cd5f2029c46b58c9d9c7f5a9e5288",
});

router.post("/stream-chat", async (req, res) => {
  const { messages } = req.body;
  res.setHeader("Content-Type", "text/plain;charset=utf-8"); //设置返回类型
  res.setHeader("Transfer-Encoding", "chunked"); //设置传输编码
  res.flushHeaders(); //发送响应头
  try {
    const completion = await openai.chat.completions.create({
      messages,
      model: "deepseek-chat",
      stream: true, //开启流式返回
    });
    // console.log(completion.choices[0].message.content);
    for await (const chunk of completion) {
      const content = chunk.choices[0]?.delta?.content;
      if (content) {
        res.write(content);
      }
    }
    res.end();
  } catch (error) {
    console.error(error);
    res.status(500).send("Stream error");
  }
});
module.exports = router;
